/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.servlet.context;

import com.luter.heimdall.core.context.WebResponseHolder;
import com.luter.heimdall.core.cookie.SimpleCookie;
import org.slf4j.Logger;

import javax.servlet.http.HttpServletResponse;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Servlet web response 功能实现
 *
 * @author luter
 */
public class ServletWebResponseHolder implements WebResponseHolder {
    private static final transient Logger log = getLogger(ServletWebResponseHolder.class);

    /**
     * The Response. servlet 响应对象，不能为空
     */
    private HttpServletResponse response;

    /**
     * Instantiates a new Servlet web response holder.
     *
     * @param response the response
     */
    public ServletWebResponseHolder(HttpServletResponse response) {
        if (null == response) {
            throw new IllegalArgumentException("WebResponseHolder init failed,HttpServletResponse can not be null");
        }
        this.response = response;
    }

    @Override
    public WebResponseHolder addCookie(SimpleCookie cookie) {
        response.addHeader(SimpleCookie.COOKIE_HEADER_NAME, cookie.toString());
        log.debug("[addCookie]::cookie = [{}]", cookie);
        return this;
    }

    @Override
    public WebResponseHolder setStatus(int statusCode) {
        response.setStatus(statusCode);
        log.debug("[setStatus]::statusCode = [{}]", statusCode);
        return this;
    }

    @Override
    public WebResponseHolder setHeader(String name, String value) {
        response.setHeader(name, value);
        log.debug("[setHeader]::name = [{}], value = [{}]", name, value);
        return this;
    }

    /**
     * Gets response.
     *
     * @return the response
     */
    public HttpServletResponse getResponse() {
        return response;
    }

    /**
     * Sets response.
     *
     * @param response the response
     * @return the response
     */
    public ServletWebResponseHolder setResponse(HttpServletResponse response) {
        if (null == response) {
            throw new IllegalArgumentException("WebResponseHolder init failed,HttpServletResponse can not be null");
        }
        this.response = response;
        return this;
    }
}
